# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'http://sf.2dcup.com/dealpay.php'
_QUERY_GATEWAY = 'http://sf.2dcup.com/dealpay_queryorder.php'

APP_CONF = {
    '10135': {
        'API_KEY': '18a082efe91778f11fce6e9731e61009'
    },
    '10151': {
        'API_KEY': '5c998cad011af3011471f1b30d70abc3'
    },
    '10217': {
        'API_KEY': '0eef96bf8bcb6700700231d5fa81d38e'
    },
    '10224': {
        'API_KEY': '06d4652d6400f7392d1b5a9cb25e3552'
    },
    '10225': {
        'API_KEY': '55a2c248dcaed6c1323797878624fdca'
    },
    '10363': {
        'API_KEY': 'b5efd1e4a1cc6ae2630b1a84216b3678'
    },
    '10364': {  # 战神 支付宝是30-3000；  快捷是单笔2万内  最低1块
        'API_KEY': '4f584e3ad20eccd2062e02ab9b60b8e5'
    },
    '10385': {  # 大菠萝 支付宝
        'API_KEY': '48cd710d20dcf0c1878e2759edca5fc5'
    },
    '10386': {  # 大菠萝 快捷
        'API_KEY': '3a19bd79832d22fc792f5c4ebe2fffd4'
    },
    '10387': {  # #大菠萝 qq
        'API_KEY': 'e75759a3878d94cbef9a3128b38b5a37'
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def generate_charge_sign(parameter, key):
    '''  生成下单签名 '''
    s = '{}{}{}{}{}'.format(
        parameter['appid'], parameter['orderid'], parameter['fee'],
        parameter['tongbu_url'], key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    _LOGGER.info(u'origin string: %s, sign:%s', s, sign)
    return sign


def build_form(params):
    html = u"<head><title>loading...</title></head><form id='youpaysubmit' name='youpaysubmit' action='" + _GATEWAY + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>document.forms['youpaysubmit'].submit();</script>"
    return html


def _get_pay_type(service):
    if service == 'alipay':
        pay_type = 22
    elif service == 'wechat':
        pay_type = 21
    elif service == 'qq':
        pay_type = 29
    elif service == 'jd':
        pay_type = 24
    elif service == 'quick':
        pay_type = 23
    else:
        pay_type = 0
    return pay_type


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    charge_resp = {}
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')  # wechat or alipay
    subject = info.get('body', 'charge')
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    parameter_dict = OrderedDict((
        ('appid', app_id),
        ('orderid', pay.id),
        ('subject', subject),
        ('fee', int(pay_amount * 100)),
        ('tongbu_url', '{}/pay/api/{}/youpay/'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH)),
        ('clientip', user_info.get('device_ip') or '172.200.110.31'),
        ('back_url', '{}/pay/api/{}/youpay/{}/'.format(
            settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('sfrom', 'wap'),
        ('paytype', _get_pay_type(service)),
        ('cpparam', '{"app_id": "%s"}' % app_id),
    ))
    parameter_dict['sign'] = generate_charge_sign(parameter_dict, api_key)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_GATEWAY, data=parameter_dict, headers=headers, timeout=10)
    resp_obj = json.loads(response.text)
    _LOGGER.info("youpay data after charge: %s", resp_obj)
    if resp_obj['code'] != 'success':
        raise ParamError('youpay create error, msg: %s' % resp_obj['msg'])
    charge_resp.update({
        'charge_info': resp_obj['msg']
    })
    return charge_resp


def verify_notify_sign(parameter, key):
    '''验证通知签名 '''
    s = '{}{}{}{}{}'.format(
        parameter['orderid'], parameter['result'], parameter['fee'],
        parameter['tradetime'], key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    calculated_sign = m.hexdigest()
    sign = parameter['sign']
    if sign != calculated_sign:
        _LOGGER.info("youpay sign: %s, calculated sign: %", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % parameter)
    return sign


def check_notify_sign(request):
    data = request.GET
    _LOGGER.info("youpay notify data: %s", data)
    cpp_param = json.loads(data['cpparam'])
    app_id = cpp_param.get('app_id')
    api_key = _get_api_key(app_id)
    verify_notify_sign(data, api_key)
    pay_id = data['orderid']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, orderid not exists, data: %s" % data)
        raise ParamError('youpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    trade_status = int(data['result'])
    mch_id = pay.mch_id
    trade_no = data['orderid']
    total_fee = float(data['fee']) / 100

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == 1:
        _LOGGER.info('youpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    api_key = _get_api_key(app_id)
    s = '{}{}{}'.format(app_id, pay_order.id, api_key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign_data = m.hexdigest()
    gate_url = '{}?orderid={}&appid={}&sign={}'.format(_QUERY_GATEWAY,
                                                       pay_order.id, app_id, sign_data)
    response = requests.get(gate_url)
    res_obj = json.loads(response.text)
    print res_obj
    result, order_id = int(res_obj['result']), res_obj['orderid']
    if str(order_id) != str(pay_order.id):
        _LOGGER.warn('youpay query order, oder id ilegal! {}-{}'.format(
            order_id, pay_order.id))
        return
    if result == 1:
        trade_no = order_id
        total_fee = float(pay_order.total_fee)
        extend = {
            'trade_status': result,
            'trade_no': order_id,
            'total_fee': total_fee
        }
        _LOGGER.info('youpay query order success, mch_id:%s pay_id:%s',
                     pay_order.mch_id, pay_order.id)
        res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                       total_fee, trade_no, extend)
        if res:
            # async notify
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('youpay query order fail, status_code: %s', result)
